{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "18bdadc9-5ccb-4635-a124-dd25b19eaaa1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import cv2\n",
    "import json\n",
    "import os.path as osp\n",
    "\n",
    "from tqdm import tqdm\n",
    "from my_class import parse_labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "20ce55af-5cb9-478b-a470-0e3fb533b2c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def yolo_to_coco(yolo_dir, save_path, split=''):\n",
    "    images_dir = osp.join(yolo_dir, 'images', split)\n",
    "    labels_dir = osp.join(yolo_dir, 'labels', split)\n",
    "    classes_path = osp.join(yolo_dir, 'classes.txt')\n",
    "    with open(classes_path, 'r') as f:\n",
    "        class_names = [line.strip() for line in f.readlines()]\n",
    "    categories = [{\"id\": i, \"name\": name} for i, name in enumerate(class_names)]\n",
    "    images = []\n",
    "    annotations = []\n",
    "    ann_id = 0\n",
    "    image_id = 0\n",
    "    for img_name in tqdm(os.listdir(images_dir)):\n",
    "        if not img_name.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):\n",
    "            continue\n",
    "        image_id += 1\n",
    "        img_path = os.path.join(images_dir, img_name)\n",
    "        img_arr = cv2.imread(img_path)\n",
    "        h, w = img_arr.shape[:2]\n",
    "        images.append({\n",
    "            \"id\": image_id,\n",
    "            \"file_name\": img_name,\n",
    "            \"width\": w,\n",
    "            \"height\": h\n",
    "        })\n",
    "\n",
    "        label_path = os.path.join(labels_dir, osp.splitext(img_name)[0] + '.txt')\n",
    "        labels = parse_labels(label_path)\n",
    "        for item in labels:\n",
    "            ann_id += 1\n",
    "            annotations.append({\n",
    "                \"id\": ann_id,\n",
    "                \"image_id\": image_id,\n",
    "                \"category_id\": int(item.category),\n",
    "                \"bbox\": (item.bbox * (w, h)).xywh,\n",
    "                \"segmentation\": (item.polygon * (w, h)).flat(),\n",
    "                \"iscrowd\": 0\n",
    "            })\n",
    "    coco_dict = {\n",
    "        \"images\": images,\n",
    "        \"annotations\": annotations,\n",
    "        \"categories\": categories\n",
    "    }\n",
    "    os.makedirs(os.path.dirname(save_path), exist_ok=True)\n",
    "    with open(save_path, 'w') as f:\n",
    "        json.dump(coco_dict, f, indent=2)\n",
    "    print(f\"✅ COCO JSON saved to: {save_path}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "24226d62-7451-46b8-a724-e0bfe498edfa",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 1869/1869 [01:46<00:00, 17.63it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ COCO JSON saved to: /data/pt/data/NikeDatasets/increasing/xiantou/annotations/instance.json\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "yolo_to_coco(\"/data/pt/data/NikeDatasets/increasing/xiantou\", \"/data/pt/data/NikeDatasets/increasing/xiantou/annotations/instance.json\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ffead1e-c735-423a-b1a1-8cace4d6a55f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
